//
//  AppUtils.m
//  InTube
//
//  Created by seven on 2019/10/29.
//  Copyright © 2019 seven. All rights reserved.
//

#import "AppUtils.h"
#import <Toast/Toast.h>
#import "ITURLManager.h"
#import "ITWebViewController.h"
#import "ITLocationManager.h"
@implementation AppUtils
+ (NSString*) appVersion {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

+(NSString *)returnBaseUrl
{
    return [[ITURLManager defaultManager] returnBaseUrl];
}


+(NSString *)returnShareH5BaseUrl
{
    NSString *baseUrl = @"https://m.intube.com";
    ITCommonConfig *webUrl = [[ITGeneralManager defaultManager] configDicWithKey:@"DICT_WEBSITE_SHARE"];
    if (webUrl && webUrl.value) {
        baseUrl = webUrl.value;
    }
    return baseUrl;
}

+(NSString *)returnAppH5BaseUrl
{
    NSString *baseUrl = @"https://www.intube.com";
    ITCommonConfig *webUrl = [[ITGeneralManager defaultManager] configDicWithKey:@"DICT_WEBSITE_BASE"];
    if (webUrl && webUrl.value) {
        baseUrl = webUrl.value;
    }
    return baseUrl;
}


+ (NSString *)configDicWithKey:(NSString *)key{
    ITCommonConfig *config = [[ITGeneralManager defaultManager] configDicWithKey:key];
    return config.value;
}


+ (UIStatusBarStyle)getDarkStyle{
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}
+ (UIStatusBarStyle)getLightStyle{
    return UIStatusBarStyleLightContent;
}

+ (UINavigationController *)findRootController{
    return (UINavigationController *)UIApplication.sharedApplication.delegate.window.rootViewController;
}

+ (ITTabBarController *)findTabbarController{
    UINavigationController *nav = [self findRootController];
    return nav.viewControllers.firstObject;
}


+ (UIViewController*)findCurrentViewController{
    return [UIViewController currentTopViewController];
}

+ (BOOL)isFirshLauch{
    int session_num = [[NSUserDefaults getValueForKey:@"session_num_key"] intValue];
    return session_num < 2;
}

+ (NSString *)titleForKey:(NSString *)key, ...{
    va_list args;
    va_start(args, key);
    NSString *suffixFormat = [[NSBundle mainBundle] localizedStringForKey:key value:@"" table:nil];
    NSString *str = [[NSString alloc] initWithFormat:suffixFormat arguments:args];
    va_end(args);
    return str;
}

+(void)showInfo:(NSString *)text{
    MainDelay(0, ^{
        [self showInfo:text position:nil];
    });
}


+(void)showInfo:(NSString *)text position:(id)position{
    MainDelay(0, ^{
        [[UIApplication sharedApplication].keyWindow showInfo:text position:position];
    });
}

+ (void)showInfo:(NSString *)text duration:(CGFloat)duration{
    MainDelay(0, ^{
        [[UIApplication sharedApplication].keyWindow makeToast:text duration:duration position:nil];
    });
}

/**
 ** lineView:       需要绘制成虚线的view
 ** lineLength:     虚线的宽度
 ** lineSpacing:    虚线的间距 0时为实线
 ** lineColor:      虚线的颜色
 **/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    [shapeLayer setLineWidth:0.5];
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}

+(NSArray *)fiterArray:(NSArray *)list fieldName:(NSString *)fieldName value:(id)value
{
    if (list) {
        if (fieldName && value) {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.%@ == %@",fieldName,value];
            NSArray *filterArr = [list filteredArrayUsingPredicate:predicate];
            return filterArr;
        }else{
            return list;
        }
    }
    return nil;
}

+ (void)trackMTAEventNo:(NSString *)eventNo{
    [ITTrackManager trackMTAEventNo:eventNo parameters:nil];
}
+ (void)trackMTAEventNo:(NSString *)eventNo parameters:(NSDictionary * IT_NULLABLE )parameters{
    [ITTrackManager trackMTAEventNo:eventNo parameters:parameters];
}

+ (BOOL)isNullStr:(NSString *)str{
    if (str == nil || [str isEqual:[NSNull null]] || str.length == 0) {
        return  YES;
    }
    
    return NO;
}

+(NSString *)getMMSSFromSS:(int)totalTime
{
    int minite = totalTime / 60;
    int second = totalTime % 60;
    NSString *str = [NSString stringWithFormat:@"%02d:%02d",minite,second];
    return str;
}

+ (MBProgressHUD *)showLoading{
    UIView *appRootView = [UIViewController currentTopViewController].view;
    return [appRootView showLoading];
}

+ (void)hideLoading{
    MainDelay(0, ^{
        UIView *appRootView = [UIApplication sharedApplication].keyWindow;
        [appRootView hideLoading];
    });
}

+ (void)pushController:(UIViewController *)uc{
    [(UINavigationController *)[self findRootController] pushViewController:uc animated:YES];
}

+ (void)pushMemberCenter:(ITMember *)member{
    BaseViewController *uc = [BaseViewController new];
    [self pushController:uc];
}

+ (void)pushWebView:(NSString *)url title:(NSString *)title{
    if (url.length == 0) {
        return;
    }
    ITWebViewController *web = [ITWebViewController openUrl:url];
    web.title = title;
}

+(void)gradientColorWithView:(UIView *)bgView startPoint:(CGPoint)startPoint toPoint:(CGPoint)toPoint fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor locations:(NSArray *)locations
{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = bgView.bounds;
    [bgView.layer insertSublayer:gradientLayer atIndex:0];
    
    //    gradientLayer.startPoint = CGPointMake(0, 0);
    //    gradientLayer.endPoint = CGPointMake(1, 0.6);
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = toPoint;
    gradientLayer.colors = @[(__bridge id)fromColor.CGColor,
                             (__bridge id)toColor.CGColor];
    gradientLayer.locations = locations;
}

+(UIImage *)getGradientImageWithColors:(NSArray*)colors imgSize:(CGSize)imgSize start:(CGPoint)start endPoint:(CGPoint)end
{
    NSMutableArray *arRef = [NSMutableArray array];
    for(UIColor *ref in colors) {
        [arRef addObject:(id)ref.CGColor];
        
    }
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)arRef, NULL);
    CGPoint startPoint = CGPointMake(imgSize.width * start.x, imgSize.height * start.y);
    CGPoint endPoint = CGPointMake(imgSize.width * end.x, imgSize.height * end.y);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

+(void)setCustomCorners:(UIView *)view roundingCorners:(UIRectCorner)corners cornerRadius:(CGFloat)radius
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius,radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

+ (BOOL)isNetworkURL:(NSString *)url
{
    if (![url isKindOfClass:[NSString class]]) {
        return NO;
    }
    BOOL result = NO;
    if (url) {
        if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]) {
            result = YES;
        }
    }
    return result;
}

+(NSString *)formatLoadUrl:(NSString *)url
{
    NSString *loadUrl = nil;
    if ([AppUtils isNetworkURL:url]) {
        loadUrl = [[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return loadUrl;
}

+ (id)objectWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    if (![jsonString isKindOfClass:[NSString class]]) {
        return jsonString;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return obj;
}

+(NSString *)getYYMMDDFromDate:(NSDate *)date
{
    if (date == nil) {
        return nil;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}
@end
